#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <mqueue.h>
#include <string.h>
#define MAX_SIZE 1024
const char *queue_name = "/test_queue";
mqd_t mqd ;
/*接收消息*/
void *first_thread_func(void *args)
{
    printf("接收消息\n");
    sleep(1);
    char recv_msg[100]={0};
    unsigned int prio;
    /*返回值：成功从消息队列中接收的数据长度*/
    ssize_t size= mq_receive(mqd,recv_msg,MAX_SIZE,&prio);/*此处传入的能接收的消息最大长度必须大于等于之前设置的最大长度*/
    if (size > 0)
    {
        printf("接收到的消息为：%s, size=%ld\n", recv_msg, size);
        mq_close(mqd);
    }
    else
    {
        printf("接收消息失败, size=%ld\n", size);
    }
}
/*发送消息*/
void *secnod_thread_func(void *args)
{
    printf("发送消息\n");
    char* msg="hello mq";
    mq_send(mqd,msg,strlen(msg)+1,0);
}


// first_thread_func,secnod_thread_func
int main(int argc, char const *argv[])
{
    struct mq_attr attr;
    attr.mq_maxmsg=10;
    attr.mq_msgsize=MAX_SIZE;
    mqd = mq_open(queue_name, O_CREAT | O_RDWR, 0644,&attr);
    if(mqd ==(mqd_t)-1){
        perror("mqd ERROR\n");
        return -1;
    }
    /*创建两个分线程*/
    pthread_t pt1, pt2;
    pthread_create(&pt1, NULL, first_thread_func, NULL);
    pthread_create(&pt2, NULL, secnod_thread_func, NULL);


    /*等待分线程执行结束*/
    pthread_join(pt1, NULL);
    pthread_join(pt2, NULL);

    printf("主线程(%d)即将结束\n", gettid());
    return 0;
}
